/*******************************************************************************
 * Copyright (c) Jonathan Buck - jonbuck16@gmail.com
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    jonbuck16@gmail.com - initial API and implementation
 *******************************************************************************/
package net.jonbuck.tassoo.persistence.ui.handler;

import net.jonbuck.tassoo.model.Task;
import net.jonbuck.tassoo.model.TassooPackage;
import net.jonbuck.tassoo.persistence.dao.TassooDaoImpl;
import net.jonbuck.tassoo.persistence.ui.nl.Messages;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.command.RemoveCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 
 * 
 * @since 1.0.0
 */
public class DeleteTaskHandler extends AbstractHandler implements IHandler {

	/**
	 * 
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		AdapterFactoryEditingDomain editingDomain = TassooDaoImpl.getInstance().getEditingDomain();

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
		Task taskToDelete = (Task) selection.getFirstElement();

		if (MessageDialog.openQuestion(Display.getCurrent().getActiveShell(), Messages.question_deletetasktitle, taskToDelete
				.getTask().size() > 0 ? Messages.question_deletetaskparent : Messages.question_deletetask)) {

			editingDomain.getCommandStack().flush();
			Object parent = getParent(taskToDelete);
			if (parent instanceof Task) {
				editingDomain.getCommandStack().execute(
						RemoveCommand.create(editingDomain, getParent(taskToDelete), TassooPackage.Literals.TASK__TASK,
								taskToDelete));
			} else {
				editingDomain.getCommandStack().execute(
						RemoveCommand.create(editingDomain, getParent(taskToDelete), TassooPackage.Literals.CONTAINER__TASK,
								taskToDelete));
			}
		}
		
		return null;
	}

	/**
	 * 
	 * @param object
	 * @return
	 */
	public Object getParent(Object object) {
		EObject eObject = (EObject) object;
		Object result = eObject.eContainer();
		if (result == null) {
			result = eObject.eResource();
		}
		return result;
	}
	
}
